package gpl.scotlandyard.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.prefs.InvalidPreferencesFormatException;
import java.util.prefs.Preferences;

/**
 * Works as Properties.
 * 
 * @author Norbert Martin
 */
public final class Config {

  private static final Preferences ROOT = Preferences.userNodeForPackage(Config.class);

  /**
   * Loads properties in conf. If some already exists they will be overwritten.
   * 
   * @param conf to load.
   * @throws IOException
   * @throws InvalidPreferencesFormatException 
   */
  public static void load(File conf) throws IOException, InvalidPreferencesFormatException {
    Preferences.importPreferences(new FileInputStream(conf));
  }

  /**
   * Loads properties in conf. If some already exists they will be overwritten.
   * The stream is closed at the end.
   * 
   * @param conf to load.
   * @throws IOException
   * @throws InvalidPreferencesFormatException 
   */
  public static void load(InputStream conf) throws IOException, InvalidPreferencesFormatException {
    Preferences.importPreferences(conf);
    conf.close();
  }

  /**
   * Gets associated value to this key, null if doesn't exist.
   * 
   * @param key
   * @return associated value or null if doesn't exist
   */
  public static String get(String key) {
    return ROOT.get(key, "");
  }

  /**
   * Gets associated value to this key and convert as int.
   * 
   * @param key
   * @return associated value as int or throws exception if doesn't exist
   * @throws NumberFormatException if result is null
   */
  public static int getInteger(String key) {
    return ROOT.getInt(key, 0);
  }

  /**
   * Gets associated value to this key and convert as boolean.
   * 
   * @param key
   * @return associated value as boolean
   */
  public static boolean getBoolean(String key) {
    return ROOT.getBoolean(key, false);
  }

  /** User node for package.
   * @return Preferences
   */
  public static Preferences userPreferences() {
    return ROOT;
  }

  private Config() {
  }
}
